package com.lagou.gateway.util;

import com.alibaba.fastjson.JSON;
import com.lagou.gateway.BaseResponseBodyEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpResponse;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.nio.charset.Charset;

public class ResponseBodyUtil {
    public static Mono<Void> writeBuffer(ServerHttpResponse resp, BaseResponseBodyEntity body){
        return resp.writeWith(
                Flux.just(body)
                        .map(
                                entity -> {
                                    String bodyStr = JSON.toJSONString(entity);
                                    byte[] newBody = bodyStr.getBytes(Charset.forName("UTF-8"));
                                    HttpHeaders headers = resp.getHeaders();
                                    if (headers.getContentLength() > 0) {
                                        headers.setContentLength(newBody.length);
                                    }

                                    return resp.bufferFactory().wrap(newBody);
                                })
        );
    }
}
